#include "Thread.h"
#include "Common.h"
#include "Lock.h"

uint g_QuitThreadCount = 0;
MyLock g_thread_lock;

Thread::Thread() {
    m_TID = 0;
    m_Status = Thread::READY;
}

Thread::~Thread() {
}

void Thread::start() {
    __ENTER_FUNCTION
    if (m_Status != Thread::READY)
        return;
    pthread_create(&m_TID, NULL, ThreadProcess, this);
    __LEAVE_FUNCTION
}

void Thread::stop() {
}

void Thread::exit(void* retval) {
    try {
        pthread_exit(retval);
    } catch (...) {
    }
}

void Thread::run() {
}


//------------------------------------------------------------------------------

void* ThreadProcess(void* derivedThread) {
    __ENTER_FUNCTION

    Thread* thread = (Thread*) derivedThread;
    if (thread == NULL)
        return NULL;

    // set thread's status to "RUNNING"
    thread->setStatus(Thread::RUNNING);
    
    // here - polymorphism used. (derived::run() called.)
    thread->run();

    // set thread's status to "EXIT"
    thread->setStatus(Thread::EXIT);

    //INT ret = 0;
    //thread->exit(&ret);

    g_thread_lock.Lock();
    g_QuitThreadCount++;
    g_thread_lock.Unlock();

    __LEAVE_FUNCTION

    return NULL; // avoid compiler's warning
}
